#include "roleadd.h"
#include "ui_roleadd.h"
#include <QDateTime>
#include <QDebug>
#include "msgbox.h"
#include "authmanager.h"
#include "frminput2019.h"
#include "userlogger.h"

RoleAdd::RoleAdd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RoleAdd)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &RoleAdd::retranslateUiSlot);

    initWidget();
}

RoleAdd::~RoleAdd()
{
    delete ui;
}

void RoleAdd::clearInput()
{
    ui->lineNewRoleName->clear();
    int count = ui->listWidget->count();
    int permission = AuthManager::instance()->basePermission("user");
    for (int r = 0; r < count; r++)
    {
        if (AuthManager::instance()->hasPermission(permission, (RolePermissionIndex)r))
        {
            ui->listWidget->item(r)->setCheckState(Qt::Checked);
        }
        else
        {
            ui->listWidget->item(r)->setCheckState(Qt::Unchecked);
        }
    }

    ui->listWidget->scrollToTop();
}

void RoleAdd::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void RoleAdd::showEvent(QShowEvent *)
{
    this->activateWindow();
}

void RoleAdd::on_btnClose_clicked()
{
    this->hide();
}

void RoleAdd::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void RoleAdd::on_btnConfirmAddRole_clicked()
{
    frmInput2019::Instance()->hideAndClearFocus();

    if (!checkRoleName())
    {
        return;
    }

    QString roleName = ui->lineNewRoleName->text().trimmed();
    int permission = AuthManager::instance()->basePermission(roleName);
    int count = ui->listWidget->count();
    for (int r = 0; r < count; r++)
    {
        if (ui->listWidget->item(r)->checkState())
        {
            permission = AuthManager::instance()->addPermission(permission, (RolePermissionIndex)r);
        }
        else
        {
            permission = AuthManager::instance()->removePermission(permission, (RolePermissionIndex)r);
        }
    }

    qDebug() << "permission = " << permission;

    role.name = roleName;
    role.permission = permission;
    QString strDatetime = currentDateTime();
    role.createDatetime = strDatetime;

    EttaError ret = sqlHelper->insertRole(role);
    if (ret == EttaError::OK)
    {
        QString permissionStr = QString("%1:").arg(tr("permission"));
        QString message = QString("%1: %2").arg(tr("Add Role")).arg(role.name);

        for (int r = 0; r < ui->listWidget->count(); r++)
        {
            if (AuthManager::instance()->hasPermission(permission, (RolePermissionIndex)r))
            {
                permissionStr += " ";
                permissionStr += ui->listWidget->item(r)->text();
            }
        }

        UserLogger::log(QString("%1\n>%2").arg(message).arg(permissionStr));
        bdf->showAllRoles(true);
        this->hide();
    }
    else
    {
        UserLogger::error(QString(tr("Failed to Add Role %1")).arg(role.name));
        QString result = (ret == EttaError::OK) ? tr("Success") : tr("Failed");
        MsgBox::information(this, tr("Add Role"), QString(tr("%1 to Add Role")).arg(result));
    }
}

void RoleAdd::initWidget()
{
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget_4->setGraphicsEffect(shadow);
    ui->lineNewRoleName->setValidator(gUsernameValidator);
    ui->lineNewRoleName->setPlaceholderText(tr("1~15 letters or numbers"));
    setWindowFlags(windowFlags() | Qt::SubWindow);
}

EttaError RoleAdd::checkRoleValid()
{
    role.name = ui->lineNewRoleName->text().trimmed();

    EttaError ret = EttaError::OK;
    if(role.name.isEmpty())
    {
        MsgBox::information(this, tr("Role"), tr("Role name cannot be empty!"));
        return EttaError::ROLE_NAME_EMPTY;
    }

    if (AuthManager::instance()->isPresetAccount(role.name))
    {
        MsgBox::information(this, tr("Role"), tr("Role name is not allowed!"));
        return EttaError::ROLE_NAME_INNER_USER;
    }

    bool state = sqlHelper->checkRoleExist(role.name);
    if(state)
    {
        MsgBox::information(this, tr("Role"), tr("This role already exists!"));
        return EttaError::ROLE_ALREADY_EXIST;
    }

    return ret;
}

bool RoleAdd::checkRoleName()
{
    if (EttaError::OK != checkRoleValid())
    {
        ui->lineNewRoleName->selectAll();
        ui->lineNewRoleName->setFocus();
        return false;
    }

    return true;
}

void RoleAdd::on_btnCancelAddRole_clicked()
{
    this->hide();
}

void RoleAdd::on_lineNewRoleName_returnPressed()
{
    checkRoleName();
}
